from bs4 import BeautifulSoup 
import re
import urllib.request
import xlwt  

#获取指定网页内容
def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.116 Safari/537.36"
    } #伪装成网页的形式，请求网页信息
    request = urllib.request.Request(url,headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)
    return html

#电影名称
findTitle = re.compile(r'<span class="title">(.*)</span>')
#评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
#评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')
#概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
#电影详细内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)


#爬取网页
def getData(网页):
    datalist = []
    for i in range(0,10):
        url = 网页 + str(i*25)
        html = askURL(url)


        #解析数据
        soup = BeautifulSoup(html,"html.parser")
        for item in soup.find_all('div',class_="item"):
            
            data = []
            item = str(item)

            Title = re.findall(findTitle,item)
            if len(Title)==2:
                ctitle = Title[0]
                data.append(ctitle)
                otitle = Title[1].replace("/","")
                data.append(otitle)
            else:
                data.append(Title[0])
                data.append(' ')

            Rating = re.findall(findRating,item)[0]
            data.append(Rating)

            Judge = re.findall(findJudge,item)[0]
            data.append(Judge)

            Inq = re.findall(findInq,item)
            if len(Inq) !=0:
                Inq = Inq[0].replace("。","")
                data.append(Inq)
            else:
                data.append(" ")

            Bd = re.findall(findBd,item)[0]
            Bd = re.sub('<br(\s+)?/>(\s+)?'," ",Bd)
            data.append(Bd.strip())

            datalist.append(data)    #把处理好的一个电影信息存储到datalist中
    
    return datalist

#储存文件函数

def savedata(datalist,savepath):
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)
    sheet = book.add_sheet('豆瓣电影Top250',cell_overwrite_ok=True)
    col = ("影片中文名","影片外国名","评分","评价数","概况","相关信息","")
    for i in range(0,6):
        sheet.write(0,i,col[i])
    for i in range(0,250):
        data = datalist[i]
        for j in range(0,6):
            sheet.write(i+1,j,data[j])
    book.save('豆瓣电影Top250.xls')

#主函数

def main():
    网页链接 = "https://movie.douban.com/top250?start="
    #爬取网页
    datalist = getData(网页链接)
    #保存数据
    savepath = "豆瓣电影Top250.xls"
    savedata(datalist,savepath)

#运行程序
main()
print("爬取完毕")


import pandas as pd  
  
import pandas as pd  
  
# 读取.xls文件  
df = pd.read_excel('豆瓣电影Top250.xls')  
  
# 将数据框写入.csv文件  
df.to_csv('豆瓣电影Top250.csv', index=False, encoding='utf-8-sig')

import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#导入表格数据并查看前五行
data=pd.read_csv(r"豆瓣电影Top250.csv")
print(data.head())

#数据描述

#查看形状
print(data.shape)

#查看列名
print(data.columns)

#查看描述性统计分析
print(data.describe())

#显示分数和评价数量
import seaborn as sns
sns.displot(data['评分'],color="r",bins=10,kde=True)
sns.displot(data['评价数'],color="b",bins=10,kde=True)
plt.show()


#数据预处理

#查找缺失数据缺失项
data=data.replace(0, np.nan)
print(data.isnull().sum(axis=0))

#删除含缺失值的行
data = data.dropna()



